/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.dataprocessing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateKindEnum;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateTypeEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.service.ICSourceDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportRecordService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonPreviewDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiCaseRecallColumnMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterMainInfo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceDocumentRecordService;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceRegisterMainInfoService;
import com.icinfo.cloud.provider.punish.dataprocessing.dto.*;
import com.icinfo.cloud.provider.punish.dataprocessing.enums.CaseSourceTypeNums;
import com.icinfo.cloud.provider.punish.dataprocessing.enums.OperationRecordNums;
import com.icinfo.cloud.provider.punish.dataprocessing.mapper.DataProcessCaseInfoOperationRecordMapper;
import com.icinfo.cloud.provider.punish.dataprocessing.model.*;
import com.icinfo.cloud.provider.punish.dataprocessing.service.*;
import com.icinfo.cloud.provider.punish.dataprocessing.vo.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 工单处理-操作日志表 data_process_case_info_operation_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2023年02月02日
 */
@Service
public class DataProcessCaseInfoOperationRecordServiceImpl extends MyBatisServiceSupport implements IDataProcessCaseInfoOperationRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(DataProcessCaseInfoOperationRecordServiceImpl.class);

    @Autowired
    private DataProcessCaseInfoOperationRecordMapper operationRecordMapper;

    @Autowired
    private ICaseMainInfoService caseMainInfoService;

    @Autowired
    private ICaseSourceRegisterMainInfoService sourceRegisterService;

    @Autowired
    private ICaseDataReportRecordService reportRecordService;

    @Autowired
    private IDataProcessDocConfigInfoService docConfigInfoService;

    @Autowired
    private ICaseDocumentRecordService documentRecordService;

    @Autowired
    private ICaseSourceDocumentRecordService sourceDocumentRecordService;

    @Autowired
    private IStageDocCommonOperateService stageDocCommonOperateService;

    @Autowired
    private ICSourceDocCommonOperateService sourceDocCommonOperateService;

    @Autowired
    IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Autowired
    private IDataProcessFieldConfigInfoService fieldConfigInfoService;

    @Resource
    private ConfigBusiCaseRecallColumnMapper recallColumnMapper;

    @Autowired
    private IDataProcessCaseSourceMainInfoDelRecordService sourceMainInfoDelRecordService;

    @Autowired
    private IDataProcessCaseMainInfoDelRecordService mainInfoDelRecordService;

    @Autowired
    private ISysDepartParamService sysDepartParamService;

    @Autowired
    private ICaseSourceDocumentRecordService caseSourceDocumentRecordService;

    /**
     * 搜索 案件/案源 信息
     *
     * @param searchDto 搜索对象
     * @return 案件/案源信息
     * @author lilihao
     * @date 2023/2/3 11:29
     */
    @Override
    public  List<DataProcessCaseInfoVo> searchCaseInfo(CaseSearchDto searchDto) {
        List<DataProcessCaseInfoVo> dataProcessInfoList = new ArrayList<>();
        if(StrUtil.isBlank(searchDto.getType())){
            return dataProcessInfoList;
        }
        //1.根据类型，查询案源/案件信息
        if (CaseSourceTypeNums.TYPE_CASE_MAIN.getCode().equals(searchDto.getType())) {
            List<CaseMainInfo> caseMainInfoList = caseMainInfoService.getCaseInfo(searchDto);
            List<DataProcessCaseMainInfoDelRecord> delCaseInfoList = mainInfoDelRecordService.getCaseInfo(searchDto);
            if (CollectionUtil.isEmpty(caseMainInfoList) && CollectionUtil.isEmpty(delCaseInfoList)) {
                return dataProcessInfoList;
            }
            if (CollectionUtil.isNotEmpty(delCaseInfoList)) {
                List<CaseMainInfo> caseMainInfoList1 = JSONUtil.toList(JSONUtil.parseArray(delCaseInfoList), CaseMainInfo.class);
                caseMainInfoList.addAll(caseMainInfoList1);
            }
            caseMainInfoList.forEach(a->{
                DataProcessCaseInfoVo dataProcessInfo = new DataProcessCaseInfoVo();
                dataProcessInfo.setId(a.getId());
                dataProcessInfo.setNumber(a.getCaseNumber());
                if (reportRecordService.isReportCase(a.getId())) {
                    dataProcessInfo.setReportStatus("已上报");
                } else {
                    dataProcessInfo.setReportStatus("未上报");
                }
                dataProcessInfo.setType(searchDto.getType());
                dataProcessInfo.setCaseName(a.getCaseName());
                dataProcessInfo.setCaseActsCode(a.getCaseActsCode());
                dataProcessInfo.setCaseCurrentLinkName(a.getCaseCurrentLinkName());
                dataProcessInfo.setCaseTypeName(CaseTypeEnum.getValueByCode(a.getCaseType()));
                dataProcessInfo.setCaseRegistTime(a.getCaseRegistTime());
                //查看最近一次案件状态
                Example example = new Example(DataProcessCaseInfoOperationRecord.class);
                example.createCriteria().andEqualTo("caseId", dataProcessInfo.getId());
                example.orderBy("createTime").desc();
                List<DataProcessCaseInfoOperationRecord> list = operationRecordMapper.selectByExample(example);
                if (CollectionUtil.isNotEmpty(list)) {
                    DataProcessCaseInfoOperationRecord operationRecord = list.get(0);
                    dataProcessInfo.setOperationType(operationRecord.getOperationType());
                    dataProcessInfo.setOperationTypeName(OperationRecordNums.getValueByCode(operationRecord.getOperationType()));
                    dataProcessInfo.setCreateUserName(operationRecord.getCreateUserName());
                    dataProcessInfo.setCreateTime(operationRecord.getCreateTime());
                    dataProcessInfo.setCaseState("1,2".contains(operationRecord.getOperationType()) ? "已被删除" : "已被修改");
                } else {
                    dataProcessInfo.setCaseState("正常");
                }
                dataProcessInfoList.add(dataProcessInfo);
            });

        } else {
            //如果案源编号不为空，案源id为空，查询并设置案源id
            if (StrUtil.isNotBlank(searchDto.getNumber())&&StrUtil.isBlank(searchDto.getId())){
                String sourceId = caseSourceDocumentRecordService.getCaseSourceIdByDocumentNumber(searchDto.getNumber());
                if (StrUtil.isBlank(sourceId)){
                    return dataProcessInfoList;
                }else {
                    searchDto.setId(sourceId);
                }
            }
            List<CaseSourceRegisterMainInfo> caseSourceRegisterInfoList = sourceRegisterService.getCaseSourceRegisterInfo(searchDto);
            List<DataProcessCaseSourceMainInfoDelRecord> delRecordList = sourceMainInfoDelRecordService.getCaseSourceRegisterInfo(searchDto);
            if (CollectionUtil.isEmpty(caseSourceRegisterInfoList) && CollectionUtil.isEmpty(delRecordList)) {
                return dataProcessInfoList;
            }
            if (CollectionUtil.isNotEmpty(delRecordList)) {
                List<CaseSourceRegisterMainInfo> list = JSONUtil.toList(JSONUtil.parseArray(delRecordList), CaseSourceRegisterMainInfo.class);
                caseSourceRegisterInfoList.addAll(list);
            }

            caseSourceRegisterInfoList.forEach(a->{
                DataProcessCaseInfoVo dataProcessInfo = new DataProcessCaseInfoVo();
                dataProcessInfo.setId(a.getId());
                dataProcessInfo.setType(searchDto.getType());
                dataProcessInfo.setCaseName(a.getCaseSourceName());
                dataProcessInfo.setCaseSourceDesc(a.getCaseSourceDesc());
                dataProcessInfo.setCaseActsCode(a.getCaseSourceAppActsCode());
                dataProcessInfo.setCaseCurrentLinkName(a.getLineName());
                if (reportRecordService.isReportCase(a.getId())) {
                    dataProcessInfo.setReportStatus("已上报");
                } else {
                    dataProcessInfo.setReportStatus("未上报");
                }
                //查看最近一次案件状态
                Example example = new Example(DataProcessCaseInfoOperationRecord.class);
                example.createCriteria().andEqualTo("caseId", dataProcessInfo.getId());
                example.orderBy("createTime").desc();
                List<DataProcessCaseInfoOperationRecord> list = operationRecordMapper.selectByExample(example);
                if (CollectionUtil.isNotEmpty(list)) {
                    DataProcessCaseInfoOperationRecord operationRecord = list.get(0);
                    dataProcessInfo.setOperationType(operationRecord.getOperationType());
                    dataProcessInfo.setOperationTypeName(OperationRecordNums.getValueByCode(operationRecord.getOperationType()));
                    dataProcessInfo.setCreateUserName(operationRecord.getCreateUserName());
                    dataProcessInfo.setCreateTime(operationRecord.getCreateTime());
                    dataProcessInfo.setCaseState("1,2".contains(operationRecord.getOperationType()) ? "已被删除" : "已被修改");
                } else {
                    dataProcessInfo.setCaseState("正常");
                }
                dataProcessInfoList.add(dataProcessInfo);
            });
        }

        return dataProcessInfoList;
    }

    /**
     * 获取操作列表
     *
     * @param detailDto 工作处理详情dto
     * @return 操作详情列表
     * @author lilihao
     * @date 2023/2/3 16:25
     */
    @Override
    public List<DataProcessOperationRecordVo> getOperationList(DataProcessCaseDetailDto detailDto) {
        //1.获取操作记录列表
        Example example = new Example(DataProcessCaseInfoOperationRecord.class);
        example.createCriteria().andEqualTo("caseId", detailDto.getCaseId());
        example.orderBy("createTime").asc();
        List<DataProcessCaseInfoOperationRecord> list = operationRecordMapper.selectByExample(example);
        List<DataProcessOperationRecordVo> operationRecordVoList = new ArrayList<>();
        list.forEach(a -> {
            DataProcessOperationRecordVo recordVo = DataProcessOperationRecordVo.builder().createTime(a.getCreateTime())
                    .operationType(a.getOperationType())
                    .createUserName(a.getCreateUserName())
                    .operationTypeName(OperationRecordNums.getValueByCode(a.getOperationType())).build();
            if (StrUtil.isNotBlank(a.getProof())) {
                List<DataProcessCaseFileVo> fileVoList = JSONUtil.toList(JSONUtil.parseArray(a.getProof()), DataProcessCaseFileVo.class);
                recordVo.setFileList(fileVoList);
            }
            operationRecordVoList.add(recordVo);
        });
        return operationRecordVoList;
    }

    /**
     * 获取案件文书列表
     *
     * @param detailDto 工作处理详情dto
     * @return 案件文书列表
     * @author lilihao
     * @date 2023/2/3 16:58
     */
    @Override
    public List<DataProcessCaseDocListVo> getCaseDocList(DataProcessCaseDetailDto detailDto) {
        List<DataProcessCaseDocListVo> docListVoList = new ArrayList<>();
        //1.获取可编辑文书字典类型
        List<DataProcessDocConfigInfo> list = docConfigInfoService.getDocumentCatalogCodeList(detailDto.getType());
        if (CollectionUtil.isEmpty(list)) {
            return docListVoList;
        }
        List<String> codeList = list.stream().map(DataProcessDocConfigInfo::getDocumentCatalogCode).collect(Collectors.toList());
        Map<String, List<DataProcessDocConfigInfo>> map = list.stream().collect(Collectors.groupingBy(DataProcessDocConfigInfo::getDocumentCatalogCode));

        //2.获取案件文书
        if (CaseSourceTypeNums.TYPE_CASE_MAIN.getCode().equals(detailDto.getType())) {
            //案件文书列表获取
            List<CaseDocumentRecord> documentRecordList = documentRecordService.getDocumentRecordList(detailDto.getCaseId(), codeList);

            documentRecordList.forEach(a -> {
                DataProcessCaseDocListVo docListVo = DataProcessCaseDocListVo.builder()
                        .docName(map.get(a.getDocumentCatalogCode()).get(0).getDocumentCatalogName())
                        .id(a.getId()).documentUrl(StrUtil.isNotBlank(a.getDocumentUrlAfterSeal())?a.getDocumentUrlAfterSeal():a.getDocumentUrl())
                        .documentContent(a.getDocumentContent())
                        .build();
                docListVoList.add(docListVo);
            });
        } else {
            //案源文书列表获取
            List<CaseSourceDocumentRecord> documentRecordList = sourceDocumentRecordService.getDocumentRecordList(detailDto.getCaseId(), codeList);
            documentRecordList.forEach(a -> {
                DataProcessCaseDocListVo docListVo = DataProcessCaseDocListVo.builder()
                        .docName(map.get(a.getDocumentCatalogCode()).get(0).getDocumentCatalogName())
                        .id(a.getId()).documentUrl(StrUtil.isNotBlank(a.getDocumentUrlAfterSeal())?a.getDocumentUrlAfterSeal():a.getDocumentUrl())
                        .documentContent(a.getDocumentContent())
                        .build();
                docListVoList.add(docListVo);
            });
        }
        //3.返回案件文书列表
        return docListVoList;
    }

    /**
     * 获取预览文书链接
     *
     * @param detailDto 请求对象
     * @return 文书链接
     * @author lilihao
     * @date 2023/2/6 16:17
     */
    @Override
    public String getPreviewDocUrl(DataProcessCaseDetailDto detailDto) {
        //根据文书内容转换文书链接
        if (CaseSourceTypeNums.TYPE_CASE_MAIN.getCode().equals(detailDto.getType())) {
            //案件转换
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(detailDto.getCaseId());
            //获取案件信息
            CaseDocumentRecordVo documentRecordVo = documentRecordService.getCaseDocumentRecordInfo(detailDto.getDocumentId());
            StageDocCommonPreviewDto saveDto = new StageDocCommonPreviewDto();
            saveDto.setCaseId(detailDto.getCaseId());
            HashMap<String, Object> map = (HashMap<String, Object>) JSONUtil.toBean(detailDto.getDocumentContent(), Map.class);
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            String templateCode = stageDocCommonOperateService.getTemplateCodeByDocumentCatalogCode(documentRecordVo.getDocumentCatalogCode(), documentRecordVo.getCaseId(), null, documentRecordVo.getPartyId());
            //老文书文书模板类型为空可能会导致预览失败
            if (Constant.STRING_2.equals(documentRecordVo.getDocumentTemplateType())) {
                pdfRequest.setTemplateType("narrow");
            } else {
                pdfRequest.setTemplateType("standard");
            }

            //判断文书模板类型是否为窄幅
            if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(documentRecordVo.getDocumentTemplateType())) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }
            //查询文书配置信息
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentRecordVo.getDocumentCatalogCode());
            //简易处罚决定书设置模板类型为窄幅
            if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }

            pdfRequest.setTemplateCode(templateCode);
            pdfRequest.setParamMap(map);
            stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
            Map<String, String> resultMap = stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
            //印章文书不为空，为文书盖章
            if (StrUtil.isNotBlank(documentRecordVo.getDocumentUrlAfterSeal())){
                String fileBase64 = resultMap.get("fileBase64");
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                String  uniscid = "";
                SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(),caseMainInfo.getCaseDeptCode());
                if (null != sysDepartParam) {
                    uniscid = sysDepartParam.getUnicode();
                }
                queryDto.setFileBase64(fileBase64);
                queryDto.setUniscid(uniscid);
                queryDto.setDeptCode(caseMainInfo.getCaseDeptCode());
                return stageDocCommonOperateService.dealFileSeal(queryDto);
            }

            String pdfUrl = String.valueOf(resultMap.get("fileUrl"));
            if (StrUtil.isNotBlank(pdfUrl)) {
                return pdfUrl;
            } else {
                logger.error("获取预览文书链接失败");
            }
        } else {
            //案源转换
            List<CaseSourceRegisterMainInfo> list = sourceRegisterService.getCaseSourceRegisterInfo(CaseSearchDto.builder().id(detailDto.getCaseId()).build());
            CaseSourceRegisterMainInfo caseSourceRegisterInfo = list.get(0);
            CaseSourceDocumentRecord sourceDocumentRecord = sourceDocumentRecordService.getDocumentRecordById(detailDto.getDocumentId());
            Map<String, Object> map = JSON.parseObject(detailDto.getDocumentContent());
            //根据文书目录编码获取模板code
            String templateCode = sourceDocCommonOperateService.getTemplateCodeByDocumentCatalogCode(sourceDocumentRecord.getDocumentCatalogCode(), sourceDocumentRecord.getCaseSourceId(), map);
            //生成未签章文书
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            pdfRequest.setTemplateCode(templateCode);
            pdfRequest.setParamMap(map);
            //判断文书模板类型是否为窄幅
            if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(sourceDocumentRecord.getDocumentTemplateType())) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }
            //查询文书配置信息
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(sourceDocumentRecord.getDocumentCatalogCode());
            //简易处罚决定书设置模板类型为窄幅
            if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
            }
            Map<String, String> resultMap = stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
            //印章文书不为空，为文书签章
            if (StrUtil.isNotBlank(sourceDocumentRecord.getDocumentUrlAfterSeal())){
                String fileBase64 = resultMap.get("fileBase64");
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                String  uniscid = "";
                SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseSourceRegisterInfo.getHandleOrgCode(),caseSourceRegisterInfo.getHandleDeptCode());
                if (null != sysDepartParam) {
                    uniscid = sysDepartParam.getUnicode();
                }
                queryDto.setFileBase64(fileBase64);
                queryDto.setUniscid(uniscid);
                queryDto.setDeptCode(caseSourceRegisterInfo.getHandleDeptCode());
                return stageDocCommonOperateService.dealFileSeal(queryDto);
            }
            String pdfUrl = String.valueOf(resultMap.get("fileUrl"));
            if (StrUtil.isNotBlank(pdfUrl)) {
                return pdfUrl;
            } else {
                logger.error("获取预览文书链接失败");
            }
        }
        return null;
    }

    /**
     * 修改文书
     *
     * @param modifyDto 修改对象
     * @return 修改结果
     * @author lilihao
     * @date 2023/2/6 16:26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result modifyCaseDoc(DataProcessDocModifyDto modifyDto) {
        //1.修改文书
        if (StrUtil.isBlank(modifyDto.getDocumentId()) || StrUtil.isBlank(modifyDto.getNewValue()) || StrUtil.isBlank(modifyDto.getNewDocUrl())) {
            return Result.error("参数缺失！");
        }
        int i;
        if (CaseSourceTypeNums.TYPE_CASE_MAIN.getCode().equals(modifyDto.getType())) {
            i = documentRecordService.modifyDocumentContent(modifyDto.getDocumentId(), modifyDto.getNewValue(), modifyDto.getNewDocUrl());
        } else {
            i = sourceDocumentRecordService.modifyDocumentContent(modifyDto.getDocumentId(), modifyDto.getNewValue(), modifyDto.getNewDocUrl());
        }
        //2.更新成功，保存操作记录
        if (i == 1) {
            DataProcessCaseInfoOperationRecord operationRecord = new DataProcessCaseInfoOperationRecord();
            operationRecord.setCaseId(modifyDto.getCaseId());
            operationRecord.setDocumentId(modifyDto.getDocumentId());
            operationRecord.setOriginalValue(modifyDto.getOriginalValue());
            operationRecord.setNewValue(modifyDto.getNewValue());
            operationRecord.setProof(JSONUtil.toJsonStr(modifyDto.getFileList()));
            operationRecord.setOperationType(OperationRecordNums.OPERATION_TYPE_MODIFY_DOC.getCode());
            saveOperationRecord(operationRecord);
            return Result.success("更新文书成功！");
        } else {
            return Result.error("更新文书失败！");
        }
    }

    /**
     * 获取字段列表
     *
     * @param detailDto 详情dto
     * @return 字段列表
     * @author lilihao
     * @date 2023/2/6 17:08
     */
    @Override
    public List<DataProcessCaseFieldListVo> getCaseFieldList(DataProcessCaseDetailDto detailDto) {
        //1.获取可修改表信息
        List<DataProcessFieldConfigInfo> list = fieldConfigInfoService.getListByType(detailDto.getType());
        List<DataProcessCaseFieldListVo> listVos = new ArrayList<>();
        Dict dict;
        CaseSearchDto caseSearchDto = CaseSearchDto.builder().id(detailDto.getCaseId()).build();
        if (CaseSourceTypeNums.TYPE_CASE_MAIN.getCode().equals(detailDto.getType())) {
            List<CaseMainInfo> caseMainInfos = caseMainInfoService.getCaseInfo(caseSearchDto);
            dict = BeanUtil.toBean(caseMainInfos.get(0), Dict.class);
        } else {
            List<CaseSourceRegisterMainInfo> caseSourceRegisterInfoList = sourceRegisterService.getCaseSourceRegisterInfo(caseSearchDto);
            dict = BeanUtil.toBean(caseSourceRegisterInfoList.get(0), Dict.class);
        }
        list.forEach(a -> {
            //获取字段值原值
            DataProcessCaseFieldListVo fieldListVo = DataProcessCaseFieldListVo.builder().fieldName(a.getFieldName())
                    .fieldChineseName(a.getFieldChineseName()).tableName(a.getTableName())
                    .tableChineseName(a.getTableChineseName())
                    .fieldType(a.getFieldType())
                    .id(a.getId()).build();
            Object o = dict.get(StrUtil.toCamelCase(a.getFieldName()));
            if (ObjectUtil.isNotNull(o)) {
                if (Constant.STRING_1.equals(a.getFieldType())) {
                    String dateStr = dateConversion(dict.getStr(StrUtil.toCamelCase(a.getFieldName())));
                    fieldListVo.setOriginalValue(dateStr);

                } else {
                    fieldListVo.setOriginalValue(String.valueOf(o));
                }
            }
            listVos.add(fieldListVo);
        });
        return listVos;
    }

    /**
     * 修改字段
     *
     * @param modifyDto 修改对象
     * @return
     * @author lilihao
     * @date 2023/2/6 17:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result modifyCaseFiled(DataProcessFiledModifyDto modifyDto) {
        if (CollectionUtil.isEmpty(modifyDto.getFileList()) || CollectionUtil.isEmpty(modifyDto.getFieldListVoList())) {
            return Result.error("参数缺失！");
        }

        //校验更新字段是否与库表一致
        boolean flag = fieldConfigInfoService.checkConsistency(modifyDto.getFieldListVoList());
        if (!flag) {
            return Result.error("更新字段与数据库配置不一致！");
        }

        //1.字段数据根据表分类(暂时当做单表)
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("UPDATE ").append(modifyDto.getFieldListVoList().get(0).getTableName())
                .append(" SET ");
        Map<String, String> oldMap = new HashMap<>();
        Map<String, String> newMap = new HashMap<>();
        modifyDto.getFieldListVoList().forEach(a -> {
            oldMap.put(a.getFieldName(), a.getOriginalValue());
            newMap.put(a.getFieldName(), a.getNewValue());
            stringBuilder.append(a.getFieldName()).append("=").append("'").append(a.getNewValue()).append("'").append(",");
        });
        String s = stringBuilder.toString();
        String sql = s.substring(0, s.length() - 1);
        sql += "WHERE  id='" + modifyDto.getCaseId() + "'";

        //2.将数据更新
        recallColumnMapper.executeUpdateSql(sql);

        //3.新增操作记录
        DataProcessCaseInfoOperationRecord operationRecord = new DataProcessCaseInfoOperationRecord();
        operationRecord.setProof(JSONUtil.toJsonStr(modifyDto.getFileList()));
        operationRecord.setRemark(modifyDto.getRemark());
        operationRecord.setCaseId(modifyDto.getCaseId());
        operationRecord.setOriginalValue(JSONUtil.toJsonStr(oldMap));
        operationRecord.setNewValue(JSONUtil.toJsonStr(newMap));
        operationRecord.setOperationType(OperationRecordNums.OPERATION_TYPE_MODIFY_FIELD.getCode());
        saveOperationRecord(operationRecord);
        return Result.success("修改成功！");
    }

    /**
     * 删除案件/案源
     *
     * @param deleteDto 删除对象
     * @return
     * @author lilihao
     * @date 2023/2/6 17:49
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteCase(DataProcessDeleteDto deleteDto) {
        DataProcessCaseInfoOperationRecord operationRecord = new DataProcessCaseInfoOperationRecord();
        CaseSearchDto caseSearchDto = CaseSearchDto.builder().id(deleteDto.getId()).build();
        if (CaseSourceTypeNums.TYPE_CASE_MAIN.getCode().equals(deleteDto.getType())) {
            //查询案件信息
            CaseMainInfo caseInfo = caseMainInfoService.getCaseInfo(caseSearchDto).get(0);
            //保存案件删除记录
            DataProcessCaseMainInfoDelRecord dataProcessCaseMainInfoDelRecord = BeanUtil.toBean(caseInfo, DataProcessCaseMainInfoDelRecord.class);
            mainInfoDelRecordService.saveRecord(dataProcessCaseMainInfoDelRecord);
            //删除案件信息
            caseMainInfoService.delCaseInfo(deleteDto.getId());

            operationRecord.setOperationType(OperationRecordNums.OPERATION_TYPE_CASE_MAIN_DEL.getCode());
        } else {
            //查询案源信息
            CaseSourceRegisterMainInfo caseSourceRegisterInfo = sourceRegisterService.getCaseSourceRegisterInfo(caseSearchDto).get(0);
            //保存案源删除记录
            DataProcessCaseSourceMainInfoDelRecord sourceDocumentRecord = BeanUtil.toBean(caseSourceRegisterInfo, DataProcessCaseSourceMainInfoDelRecord.class);
            sourceMainInfoDelRecordService.saveRecord(sourceDocumentRecord);
            //删除案源信息
            sourceRegisterService.delCaseSourceRegisterInfo(deleteDto.getId());
            operationRecord.setOperationType(OperationRecordNums.OPERATION_TYPE_CASE_SOURCE_MAIN_DEL.getCode());
        }
        operationRecord.setProof(JSONUtil.toJsonStr(deleteDto.getFileList()));
        operationRecord.setRemark(deleteDto.getRemark());
        operationRecord.setCaseId(deleteDto.getId());
        saveOperationRecord(operationRecord);
        return Result.success("删除成功！");
    }

    /**
     * 保存操作记录
     *
     * @author lilihao
     * @date 2023/2/9 10:41
     */
    private void saveOperationRecord(DataProcessCaseInfoOperationRecord operationRecord) {
        UserDTO userInfo = UserUtil.getUserInfo();
        operationRecord.setCreateUserId(String.valueOf(userInfo.getUserId()));
        operationRecord.setCreateUserName(userInfo.getRealName());
        operationRecord.setId(BaseUtil.createUid());
        operationRecord.setCreateTime(new Date());
        operationRecordMapper.insert(operationRecord);
    }

    /**
     * 日期转换
     *
     * @param dateStr 日期字符串
     * @return 转换后字符串
     * @author lilihao
     * @date 2023/2/9 18:05
     */
    private String dateConversion(String dateStr) {
        String replace = dateStr.replace("T", " ");
        int length = replace.length();
        if (length == 10) {
            replace += " 00:00:00";
        } else if (length == 13) {
            replace += ":00:00";
        } else if (length == 16) {
            replace += ":00";
        }
        return replace;
    }
}